﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SlamCms.SharePointServices.Search
{
	public class Query
	{
		public int Count
		{
			get;
			set;
		}

		public bool IncludeRelevantResults
		{
			get;
			set;
		}

		public bool IncludeSpecialTermsResults
		{
			get;
			set;
		}

		private List<string> _properties;
		public List<string> Properties
		{
			get
			{
				return _properties;
			}
		}

		public string QueryText
		{
			get;
			set;
		}

		public int StartItemIndex
		{
			get;
			set;
		}

		public Query()
		{
			_properties = new List<string>();
			IncludeRelevantResults = true;
			IncludeSpecialTermsResults = true;
			StartItemIndex = 1;
			Count = 10000;
		}

		public override string ToString()
		{
			return ToXml().ToString();
		}

		public XElement ToXml()
		{
			XElement propertiesElement = new XElement("Properties");
			foreach (string property in Properties)
			{
				propertiesElement.Add(new XElement("Property", new XAttribute("name", property)));
			}

			XElement queryElement = new XElement("Query", 
										new XElement("Context", 
											new XElement("QueryText", new XAttribute("language", "en-US"), new XAttribute("type", "MSSQLFT"), new XText(QueryText))),
										new XElement("SupportedFormats", new XAttribute("Format", "urn:Microsoft.Search.Response.Document.Document")),
										new XElement("ResultProvider", new XText("SharepointSearch")),
										new XElement("Range", 
											new XElement("StartAt", new XText(StartItemIndex.ToString())),
											new XElement("Count", new XText(Count.ToString()))),
										new XElement("EnableStemming", new XText("true")),
										new XElement("EnableSpellCheck", new XText("Off")),
										new XElement("IncludeSpecialTermsResults", new XText(IncludeSpecialTermsResults.ToString().ToLower())),
										new XElement("IncludeRelevantResults", new XText(IncludeRelevantResults.ToString().ToLower())),
										new XElement("ImplicitAndBehavior", new XText("true")),
										new XElement("TrimDuplicates", new XText("true")),
										propertiesElement
										);
			return queryElement;
		}
	}
}
